package net.qhzw.vip.qiyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.qhzw.vip.qiyu.dto.CommunityDto;
import net.qhzw.vip.qiyu.entity.Shop;
import net.qhzw.vip.qiyu.entity.SysCommunity;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.result.PageResult;
import net.qhzw.vip.qiyu.service.ShopService;
import net.qhzw.vip.qiyu.service.SysCommunityService;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("sys/communitys")
@Api(tags = "站点管理")
public class CommunityController {


    @Autowired
    private SysCommunityService communityService;

    @ApiOperation(value = "分页查询社区")
    @GetMapping
    public JsonResult<PageResult<CommunityDto>> findByPage(Page<SysCommunity> page, String name) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        PageResult<CommunityDto> communityDtoPage = communityService.findByPage(page, name, shopId);
        return JsonResult.ok(communityDtoPage);
    }

    @ApiOperation(value = "查询")
    @GetMapping("{id}")
    public JsonResult getCommunity(@PathVariable Long id) {
        SysCommunity community = communityService.getById(id);
        return JsonResult.ok(community);
    }


    @ApiOperation(value = "修改社区信息")
    @PutMapping
    public JsonResult updateCommunity(@RequestBody SysCommunity community) {
        boolean update = communityService.updateById(initDB(community));
        if (update) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "添加社区")
    @PostMapping
    public JsonResult addCommunity(@RequestBody @Validated SysCommunity community) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        community.setShopId(shopId);
        SysCommunity communityDB = initDB(community);
        boolean save = communityService.save(communityDB);
        if (save) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    /***
     * 初始化参数,校验参数
     * @param community
     * @return
     */
    private SysCommunity initDB(SysCommunity community) {
        int count = communityService.count(new LambdaQueryWrapper<SysCommunity>()
                .eq(SysCommunity::getName, community.getName()));
        community.setModifyBy(SecurityUtils.getUserId());
        if (community.getId() == null) {
            if (count > 0) {
                throw new MyException("站点名称已存在!");
            }
            community.setId(IdWorker.getId());
            community.setCreated(new Date());
            return community;
        }
        if (count > 1) {
            throw new MyException("站点名称已存在!");
        }
        return community;
    }


    @ApiOperation(value = "删除社区")
    @DeleteMapping("{id}")
    public JsonResult addCommunity(@PathVariable String id) {
        boolean remove = communityService.removeById(id);
        if (remove) {
            return JsonResult.ok();
        }
        return JsonResult.fail();
    }


    @ApiOperation(value = "生成社区二维码")
    @PostMapping("createQrCode/{id}")
    public JsonResult createQrCode(@PathVariable String id) {
        String qrCode = communityService.createQrCode(id);
        return JsonResult.ok(qrCode);
    }

    /**
     * 用于二维码
     *
     * @param id
     * @return
     */
    @GetMapping("/getCommunityById/{id}")
    public SysCommunity getCommunityById(@PathVariable String id) {
        return communityService.getById(id);
    }


    /***
     * 查询社区列表
     * @param businessType 业务类型查询
     * @param keywords 关键字查询
     * @param type 1:后台请求 2:小程序管理员请求 3:小程序用户请求
     * @return
     */
    @ApiOperation(value = "查询社区id name下拉框")
    @GetMapping("/label")
    public JsonResult<List<SysCommunity>> queryBox(@RequestParam(required = false) Byte businessType,
                                                   @RequestParam(required = false) String keywords,
                                                   @RequestParam(required = false) Byte type) {
        LambdaQueryWrapper<SysCommunity> queryWrapper = new LambdaQueryWrapper<SysCommunity>()
                .eq(SysCommunity::getStatus, 1)
                .eq(businessType != null, SysCommunity::getBusinessType, businessType)
                .and(!StringUtils.isEmpty(keywords),
                        wq -> wq.like(SysCommunity::getAddress, keywords)
                                .or()
                                .like(SysCommunity::getName, keywords)
                                .or()
                                .like(SysCommunity::getSiteManager, keywords));
        if (1 == type) {
            Long shopId = SecurityUtils.getLoginUser().getShopId();
            queryWrapper.eq(shopId != 1, SysCommunity::getShopId, shopId);
            List<SysCommunity> list = communityService.list(queryWrapper);
            return JsonResult.ok(list);
        } else if (2 == type) {
            queryWrapper.ne(SysCommunity::getBusinessType, -1);
            List<SysCommunity> list = communityService.list(queryWrapper);
            return JsonResult.ok(communityList(list));
        }
        return JsonResult.ok();
    }

    @Autowired
    private ShopService shopService;

    private List<SysCommunity> communityList(List<SysCommunity> list) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        List<Long> shopIds = list.stream().map(SysCommunity::getShopId).collect(Collectors.toList());
        List<Shop> shops = shopService.listByIds(shopIds);
        if (CollectionUtils.isEmpty(shops)) {
            return list;
        }
        for (SysCommunity community : list) {
            for (Shop shop : shops) {
                if (!community.getShopId().equals(shop.getShopId())) {
                    continue;
                } else {
                    community.setName(shop.getShortName() + "-" + community.getName());
                }
            }
        }
        return list;
    }


    @ApiOperation(value = "根据dtsUserId查询维修站点")
    @GetMapping("getByUserId/{dtsUserId}")
    public SysCommunity findByDtsUserId(@PathVariable Long dtsUserId) {
        return communityService.findByDtsUserId(dtsUserId);
    }


}
